package it.win4buy.controllers
{
	import flash.events.IEventDispatcher;
	import flash.utils.flash_proxy;
	
	import flashx.textLayout.tlf_internal;
	
	import it.win4buy.entities.UserDataVO;
	import it.win4buy.events.AlertComponentEvent;
	import it.win4buy.events.GetFlashVarsEvent;
	import it.win4buy.events.GetPlaceHolderEvent;
	import it.win4buy.events.GetStartuPlaceHolderListEvent;
	import it.win4buy.events.GetUserDataEvent;
	import it.win4buy.events.NavigationEvent;
	import it.win4buy.events.PlaceHolderEvent;
	import it.win4buy.events.UtilityEvent;
	import it.win4buy.models.ApplicationModel;
	import it.win4buy.presentations.AlertComponentPM;
	import it.win4buy.presentations.PlaceHolderViewPM;
	import it.win4buy.services.GetFlashVarsService;
	import it.win4buy.services.GetPlaceHolderService;
	import it.win4buy.services.GetStartupPlaceHolderService;
	import it.win4buy.services.GetUserDataService;
	import it.win4buy.utility.ApplicationConstants;
	import it.win4buy.utility.LoggerUtilty;
	
	import mx.controls.Alert;
	import mx.core.mx_internal;
	import mx.utils.ObjectUtil;
	
	import spark.components.Application;
	
	
	
	/**
	 *
	 *	autore:
	 *  pierangelo.mancusi@gmail.com
	 *
	 */
	
	public class StartupController
	{
		
		
		private const className:String="StartupController";
		
		
		//-------------------------------------------
		//
		// Injected properties
		//
		//-------------------------------------------
		
		[Dispatcher]
		public var dispatcher:IEventDispatcher;
		
		[Inject]
		public var applicationModel:ApplicationModel;
		
		[Inject]
		public var placeHolderPM:PlaceHolderViewPM;
		
		[Inject]
		public var log:LoggerUtilty;
		
		[Inject]
		/**
		 * Read Application Flash Vars
		 */
		public var getFlashVarsService:GetFlashVarsService;
		
		
		[Inject]
		/**
		 * Get User Data Aoocount from the Server
		 */
		public var getUserDataService:GetUserDataService;
		
		[Inject]
		public var pollingController:PollingController;
		
		[Inject]
		public var startupPlaceHolderService:GetStartupPlaceHolderService;
		
		[Inject]
		public var getPlaceHolderService:GetPlaceHolderService;
		
		[Inject]
		public var alertComponentPM:AlertComponentPM;
		
		public var applicationReference:Application;
		
		
		
		//-------------------------------------------
		//
		// Constructor
		//
		//-------------------------------------------
		
		public function StartupController()
		{
			
			
		}
		
		//-------------------------------------------
		//
		// Mediator Handlers
		//
		//-------------------------------------------
		
		[PostConstruct]
		public function init():void
		{
			log.logToConsole(this, "####################################");
			log.logToConsole(this, "####     Application init()     ####");
			log.logToConsole(this, "####################################");
			
			
			dispatcher.dispatchEvent(new NavigationEvent(NavigationEvent.VIEW_PLACEHOLDER_ALERT, null, true));
			
			alertComponentPM.btConfirmVisible=false;
			alertComponentPM.btCancelVisible=false;
			alertComponentPM.message="inizializzazione...";
			alertComponentPM.title="info.";
			
			
			//get flash vars
			getFlashVarsService.execute(applicationReference);
			
			
		}
		
		
		//-------------------------------------------
		//
		// Public Methods: EventHandlers
		//
		//-------------------------------------------
		
		//------------------------------------------------------------------------------
		//
		//
		// FlashVars Handler	
		//
		//
		//------------------------------------------------------------------------------
		
		[EventHandler(event="GetFlashVarsEvent.APPLICATION_MODE_RESULT", priority="990")]
		[EventHandler(event="GetFlashVarsEvent.APPLICATION_MODE_FAULT", priority="990")]
		public function flashVarsApplicationModeResult(event:GetFlashVarsEvent):void
		{
			switch (event.type)
			{
				case GetFlashVarsEvent.APPLICATION_MODE_RESULT:
					
					//store the applicationMode in the Model
					var t:String=event.obj as String;
					
					applicationModel.applicationState=int(t);
					
					//fixme:testing purpose
					//applicationModel.applicationState=0;
					
					startup();
					
					break;
				
				case GetFlashVarsEvent.APPLICATION_MODE_FAULT:
					
					
					log.logToConsole(this, "flashVarsResult: FlashVar 'applicationMode' not present.");
					
					alertComponentPM.btConfirmVisible=true;
					alertComponentPM.btCancelVisible=false;
					alertComponentPM.message="applicationMode assente."+"\n\n"+"Contattare il Servizio Clienti.";
					alertComponentPM.title="Errore.";
					break;
			}
		}
		
		
		[EventHandler(event="GetFlashVarsEvent.USERID_RESULT", priority="990")]
		[EventHandler(event="GetFlashVarsEvent.USERID_FAULT", priority="990")]
		public function flashVarsUserIdResult(event:GetFlashVarsEvent):void
		{
			switch (event.type)
			{
				case GetFlashVarsEvent.USERID_RESULT:
					
					//store data in the ApplicatioModel
					applicationModel.userData.userId=event.obj as String;
					log.logToConsole(this, "userId: " + applicationModel.userData.userId);
					
					
					break;
				
				case GetFlashVarsEvent.USERID_FAULT:
					
					//fixme:testing purpose
					//continue
					//it should be notified through an alert or somethig 
					log.logToConsole(this, "flashVarsResult: FlashVar  not present.");
					break;
			}
		}
		
		
		//------------------------------------------------------------------------------
		//
		//
		// Users Handler	
		//
		//
		//------------------------------------------------------------------------------
		
		[EventHandler(event="GetUserDataEvent.RESULT", priority="990")]
		[EventHandler(event="GetUserDataEvent.FAULT", priority="990")]
		public function userDataResult(event:GetUserDataEvent):void
		{
			switch (event.type)
			{
				case GetUserDataEvent.RESULT:
					
					if(event.obj != null)
					{
						log.logToConsole(this, "retrieving UseData....OK");
						applicationModel.userData=event.obj as UserDataVO;
						alertComponentPM.message="leggo i dati dell'utente...OK";
						alertComponentPM.message="leggo la lista dei tavoli...";
						//get place Holder List for only the first time
						startupPlaceHolderService.execute();
						
					}
					else
					{
						log.logToConsole(this, "retrieving UseData....KO");
						
						alertComponentPM.btConfirmVisible=true;
						alertComponentPM.btCancelVisible=false;
						alertComponentPM.message="GetUseData() failed."+"\n"+"event.obj=null."+"\n"+"Contattare il Servizio Clienti.";
						alertComponentPM.title="Errore.";
					}
					break;
				
				case GetUserDataEvent.FAULT:
					
					
					log.logToConsole(this, "flashVarsResult: FlashVar 'UseData' not present.");
					alertComponentPM.btConfirmVisible=true;
					alertComponentPM.btCancelVisible=false;
					alertComponentPM.message="GetUseData() failed."+"\n"+"Contattare il Servizio Clienti."+"\n"+event.obj.toString();
					alertComponentPM.title="Errore.";
					break;
			}
			
			
			
		}
		
		//------------------------------------------------------------------------------
		//
		//
		// PlaceHolder Handler	
		//
		//
		//------------------------------------------------------------------------------
		[EventHandler(event="GetStartuPlaceHolderListEvent.RESULT", priority="990")]
		[EventHandler(event="GetStartuPlaceHolderListEvent.FAULT", priority="990")]
		public function placeHolderStartupResult(event:GetStartuPlaceHolderListEvent):void
		{
			switch (event.type)
			{
				case GetStartuPlaceHolderListEvent.RESULT:
					log.logToConsole(this, "placeHolderResult(): event.type = GetPlaceHolderEvent.RESULT");
					
					
					if (event.placeHolder != null)
					{
						alertComponentPM.message="leggo la lista dei tavoli...OK";
						applicationModel.placeHolderList=event.placeHolder;
						
						alertComponentPM.message="PollingController started...";
						//starts the Polling Controller
						pollingController.init();
						
						// refresh Datagrid.dataProvider.
						// see PlaceHolderViewPM.as
						dispatcher.dispatchEvent(new PlaceHolderEvent(PlaceHolderEvent.STARTUP_REFRESH_PLACEHOLDER, "refreshStartupDatagrid", true));
						
						dispatcher.dispatchEvent(new NavigationEvent(NavigationEvent.VIEW_PLACEHOLDER_MAIN, null, true));
					}
					else
					{
						alertComponentPM.btConfirmVisible=true;
						alertComponentPM.btCancelVisible=false;
						alertComponentPM.message="GetStartuPlaceHolderList() failed."+"\n\n"+"Contattare il Servizio Clienti.";
						alertComponentPM.title="Errore.";
						
					}
					break;
				
				case GetStartuPlaceHolderListEvent.FAULT:
					log.logToConsole(this, "placeHolderResult(): event.type= GetPlaceHolderEvent.FAULT");
					alertComponentPM.btConfirmVisible=true;
					alertComponentPM.btCancelVisible=false;
					alertComponentPM.message="GetPlaceHolderList() failed."+"\n\n"+"Contattare il Servizio Clienti.";
					alertComponentPM.title="Errore.";
					break;
			}
			
			
			
			
			
			
		}
		
		
		
		//-------------------------------------------
		//
		// Private Methods
		//
		//-------------------------------------------
		
		private function startup():void
		{
			
			log.logToConsole(this, "#####################################################");
			
			log.logToConsole(this, "####     Application Mode: [" + applicationModel.applicationState + "]  ####");
			log.logToConsole(this, "#####################################################");
			log.logToConsole(this, "#### STARTUP's Operations for MODE: " + applicationModel.applicationState + "  starting...");
			log.logToConsole(this, "#####################################################");
			
			
			if (applicationModel.applicationState == ApplicationConstants.APPLICATION_STATE_PLACEHOLDER)
			{
				//PLACEHOLDER MODE
				
				//set the first view
				dispatcher.dispatchEvent(new NavigationEvent(NavigationEvent.VIEW_AC_PLACEHOLDER, null, true));
				
				
				
				alertComponentPM.message="leggo i dati dell'utente...";
				alertComponentPM.title="info.";
				//get User Data
				getUserDataService.execute(applicationModel.userData);
				
				
				
			}
				
			else
			{
				//sets Application PLAY MODE
				dispatcher.dispatchEvent(new NavigationEvent(NavigationEvent.VIEW_AC_PLAY, null, true));
				dispatcher.dispatchEvent(new UtilityEvent(UtilityEvent.STARTUP_PLAY_MODE, "startup", true));
				
				
			}
			
			
			
			
			
		}
		
		
		/**
		 * Force Refreshing DataBinding in the application
		 *
		 */
		private function refreshDataBinding():void
		{
			
			dispatcher.dispatchEvent(new UtilityEvent(UtilityEvent.REFRESH_BINDING, null, true));
			
		}
		
	}
}